/* eslint-disable no-prototype-builtins */
const { objIncludeOtherObj } = require('./obj-utils')

// Utility to match GraphQL mutation based on the operation name
export const hasOperationName = (req, operationName) => {
  const { body } = req
  return body.hasOwnProperty('operationName') && body.operationName === operationName
}

// Alias query if operationName matches
export const aliasQueryWithOperation = (req, operationName) => {
  if (hasOperationName(req, operationName)) {
    req.alias = `gql${operationName}Query`
  }
}

// Alias mutation if operationName matches
export const aliasMutationWithOperation = (req, operationName) => {
  if (hasOperationName(req, operationName)) {
    req.alias = `gql${operationName}Mutation`
  }
}

export const hasQuery = (req, queryName) => {
  const { body } = req
  return body.hasOwnProperty('query') && body.query.indexOf(queryName) !== -1
}

// 校验 variables
export const hasQueryAndVariables = (req, queryName, variables) => {
  const { body } = req
  return (
    body.hasOwnProperty('query') &&
    body.query.indexOf(queryName) !== -1 &&
    body.hasOwnProperty('variables') &&
    objIncludeOtherObj(body.variables, variables)
  )
}

// Alias query if no operationName
export const aliasQuery = (req, queryName, variables = null) => {
  if (variables) {
    if (hasQueryAndVariables(req, queryName, variables)) {
      req.alias = `${queryName}GqlQueryVars`
    }
  } else {
    if (hasQuery(req, queryName)) {
      req.alias = `${queryName}GqlQuery`
    }
  }
}
